/**
 * 
 */
package com.alstudio.view.edittext;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.CycleInterpolator;
import android.view.animation.TranslateAnimation;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.alstudio.utils.log.ALLog;
import com.loovee.imaohu.R;

/**
 * @author alonso lee
 * 
 */
public class ALEditText extends EditText implements OnEditorActionListener {

	public interface OnALEditorActionListener {
		// 回车键按下事件
		public void onEditorAction();

		// 输入框内容清除事件
		public void onContentClear();

		// 输入框有内容输入
		public void onContentChange(String content);
	}

	private OnALEditorActionListener mALEditorActionListener;

	private boolean showClearDrawable = true;

	/**
	 * @param context
	 */
	public ALEditText(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		init();
	}

	/**
	 * @param context
	 */
	public ALEditText(Context context, AttributeSet atts) {
		super(context, atts);
		// TODO Auto-generated constructor stub
		init();

	}

	public ALEditText(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init();
	}

	private void init() {
		setOnEditorActionListener(this);

		// getCompoundDrawables:
		// Returns drawables for the left, top, right, and bottom borders.
		Drawable[] drawables = this.getCompoundDrawables();

		// 取得right位置的Drawable
		// 即我们在布局文件中设置的android:drawableRight
		mRightDrawable = drawables[2];

		if (mRightDrawable == null) {
			mRightDrawable = getResources().getDrawable(
					R.drawable.personal_enter_botton_remove);
		}
		// 显示在右边
		mRightDrawable.setBounds(0, 0, mRightDrawable.getIntrinsicWidth(),
				mRightDrawable.getIntrinsicHeight());

		// 设置焦点变化的监听
		this.setOnFocusChangeListener(new FocusChangeListenerImpl());
		// 设置EditText文字变化的监听
		this.addTextChangedListener(new TextWatcherImpl());
		// 初始化时让右边clean图标不可见
		setClearDrawableVisible(false);
	}

	/**
	 * @param mALEditorActionListener
	 *            the mALEditorActionListener to set
	 */
	public void setALEditorActionListener(
			OnALEditorActionListener aLEditorActionListener) {
		this.mALEditorActionListener = aLEditorActionListener;
	}

	public void goneClearDrawable() {
		showClearDrawable = false;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * android.widget.TextView.OnEditorActionListener#onEditorAction(android
	 * .widget.TextView, int, android.view.KeyEvent)
	 */
	@Override
	public boolean onEditorAction(TextView paramTextView, int paramInt,
			KeyEvent paramKeyEvent) {
		// TODO Auto-generated method stub

		if (paramInt == EditorInfo.IME_ACTION_SEARCH
				|| paramKeyEvent.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
			if (mALEditorActionListener != null) {
				mALEditorActionListener.onEditorAction();
				ALLog.d("回调回车键点击事件发生");
			}
			return true;
		}

		return false;
	}

	private Drawable mRightDrawable;
	private boolean isHasFocus;

	/**
	 * 当手指抬起的位置在clean的图标的区域 我们将此视为进行清除操作 getWidth():得到控件的宽度
	 * event.getX():抬起时的坐标(改坐标是相对于控件本身而言的)
	 * getTotalPaddingRight():clean的图标左边缘至控件右边缘的距离
	 * getPaddingRight():clean的图标右边缘至控件右边缘的距离 于是: getWidth() -
	 * getTotalPaddingRight()表示: 控件左边到clean的图标左边缘的区域 getWidth() -
	 * getPaddingRight()表示: 控件左边到clean的图标右边缘的区域 所以这两者之间的区域刚好是clean的图标的区域
	 */
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		switch (event.getAction()) {
		case MotionEvent.ACTION_UP:

			boolean isClean = (event.getX() > (getWidth() - getTotalPaddingRight()))
					&& (event.getX() < (getWidth() - getPaddingRight()));
			if (isClean) {
				setText("");
				// 回调通知数据已被清除
				if (mALEditorActionListener != null) {
					mALEditorActionListener.onContentClear();
				}
			}
			break;

		default:
			break;
		}
		return super.onTouchEvent(event);
	}

	private class FocusChangeListenerImpl implements OnFocusChangeListener {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
			isHasFocus = hasFocus;
			if (isHasFocus) {
				boolean isVisible = getText().toString().length() >= 1;
				setClearDrawableVisible(isVisible);
			} else {
				setClearDrawableVisible(false);
			}
		}

	}

	// 当输入结束后判断是否显示右边clean的图标
	private class TextWatcherImpl implements TextWatcher {
		@Override
		public void afterTextChanged(Editable s) {
			boolean isVisible = getText().toString().length() >= 1;
			setClearDrawableVisible(isVisible);
			if (mALEditorActionListener != null) {
				mALEditorActionListener.onContentChange(getText().toString());
			}
		}

		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {

		}

		@Override
		public void onTextChanged(CharSequence s, int start, int before,
				int count) {

		}

	}

	// 隐藏或者显示右边clean的图标
	protected void setClearDrawableVisible(boolean isVisible) {
		Drawable rightDrawable;
		if (isVisible) {
			rightDrawable = mRightDrawable;
		} else {
			rightDrawable = null;
		}
		if (!showClearDrawable) {
			rightDrawable = null;
		}

		// 使用代码设置该控件left, top, right, and bottom处的图标
		setCompoundDrawables(getCompoundDrawables()[0],
				getCompoundDrawables()[1], rightDrawable,
				getCompoundDrawables()[3]);
	}

	// 显示一个动画,以提示用户输入
	public void setShakeAnimation() {
		this.setAnimation(shakeAnimation(5));
	}

	// CycleTimes动画重复的次数
	public Animation shakeAnimation(int CycleTimes) {
		Animation translateAnimation = new TranslateAnimation(0, 10, 0, 10);
		translateAnimation.setInterpolator(new CycleInterpolator(CycleTimes));
		translateAnimation.setDuration(1000);
		return translateAnimation;
	}

}
